package com.jy.installtool;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;

import com.android.corestat.utils.StatUtils;
import com.jy.appmarket.R;
import com.jy.appmarket.screenlock.utils.BaseInfoHelper;
import com.jy.appmarket.utils.PackageUtils;

public class InstallResultActivity extends Activity {
	private static final String EXTRA_INSTALL_RESULT = "install_result";
	private static final int CODE_SUCCESS = 0;
	private static final int CODE_FAIL = 1;

	private View mWindowView;
	private WindowManager mWinManager = null;
	private WindowManager.LayoutParams mWinParams;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.window_install_result);

		int result = getInstallResult();
		switch (result) {
		case CODE_SUCCESS:
			showInstallResult(CODE_SUCCESS, "成功", "");
			break;
		case CODE_FAIL:
			showInstallResult(CODE_FAIL, "失败", "安装失败，请恢复出厂设置重试！");
			break;
		default:
			checkInstallResult();
			break;
		}

	}

	private int getInstallResult() {
		if (getIntent() != null) {
			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				return extras.getInt(EXTRA_INSTALL_RESULT);
			}
		}
		return -1;
	}

	private void checkInstallResult() {
		String installInfoStr = StatUtils.getApkInstallInfo(this);
		JSONObject installInfoObj = null;
		ArrayList<String> list = new ArrayList<String>();
		try {
			if (StatUtils.isJson(installInfoStr)) {
				installInfoObj = new JSONObject(installInfoStr);
			}

			if (installInfoObj != null) {
				JSONArray watchArray = installInfoObj.getJSONArray("install_apks");
				for (int i = 0; i < watchArray.length(); i++) {
					JSONObject item = watchArray.getJSONObject(i);
					list.add(item.getString("name"));
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		if (list.size() == 0) {
			showInstallResult(CODE_FAIL, "失败", "安装失败，没有找到安装信息，请恢复出厂设置重试！");
			return;
		}

		ArrayList<String> unInstallList = new ArrayList<String>();
		for (int i = 0; i < list.size(); i++) {
			String pkgName = list.get(i);
			if (!PackageUtils.isPackageInstalled(this, pkgName)) {
				unInstallList.add(pkgName);
			}
		}

		// int minUnInstallCount = (int) (list.size() * 0.2);
		int minUnInstallCount = 0;
		if (unInstallList.size() > minUnInstallCount) {
			showInstallResult(CODE_FAIL, "失败", "安装失败，请恢复出厂设置重试！");
		} else {
			showInstallResult(CODE_SUCCESS, "成功", "");
		}
	}

	private void showInstallResult(int code, String title, String detail) {
		showInstallResultByWindow(code, title, detail);
		showInstallResultByActivity(code, title, detail);
	}

	private void showInstallResultByWindow(int code, String title, String detail) {
		initWinParams();

		mWindowView = LayoutInflater.from(this).inflate(R.layout.window_install_result, null);
		TextView titleTv = mWindowView.findViewById(R.id.title);
		TextView detailTv = mWindowView.findViewById(R.id.detail);

		mWindowView.findViewById(R.id.close_bn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		switch (code) {
		case CODE_SUCCESS:
			mWindowView.setBackgroundColor(Color.GREEN);
			break;
		case CODE_FAIL:
			mWindowView.setBackgroundColor(Color.RED);
			break;
		}
		titleTv.setText(title);
		detailTv.setText(detail);

		mWinManager.addView(mWindowView, mWinParams);
	}

	private void showInstallResultByActivity(int code, String title, String detail) {
		TextView titleTv = findViewById(R.id.title);
		TextView detailTv = findViewById(R.id.detail);
		findViewById(R.id.close_bn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		switch (code) {
		case CODE_SUCCESS:
			getWindow().getDecorView().setBackgroundColor(Color.GREEN);
			break;
		case CODE_FAIL:
			getWindow().getDecorView().setBackgroundColor(Color.RED);
			break;
		}
		titleTv.setText(title);
		detailTv.setText(detail);
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	private void initWinParams() {
		mWinManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
		mWinParams = new WindowManager.LayoutParams();
		mWinParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;

		mWinParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_DISMISS_KEYGUARD
				| LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_LAYOUT_IN_SCREEN
				| LayoutParams.FLAG_HARDWARE_ACCELERATED | LayoutParams.FLAG_LAYOUT_NO_LIMITS;

		mWinParams.flags |= LayoutParams.FLAG_FULLSCREEN;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			mWinParams.flags |= LayoutParams.FLAG_TRANSLUCENT_STATUS;
			mWinParams.flags |= LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
		}
		mWinParams.width = WindowManager.LayoutParams.MATCH_PARENT;
		final Display display = mWinManager.getDefaultDisplay();
		mWinParams.height = BaseInfoHelper.getRealHeight(display);

		mWinParams.x = 0;
		mWinParams.y = 0;
		mWinParams.format = PixelFormat.TRANSPARENT;
		// params.format=PixelFormat.RGBA_8888;
		mWinParams.windowAnimations = R.style.anim_locker_window;
		mWinParams.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN;
		mWinParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
		mWinParams.gravity = Gravity.TOP | Gravity.START;
	}

	@Override
	protected void onDestroy() {
		if (mWinManager != null && mWindowView != null) {
			mWinManager.removeView(mWindowView);
		}
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
	}

}
